<template>
  <div class="common-layout">
    <el-form class="header" :model="queryParam" ref="queryRef" :inline="true">
      <el-form-item label="组号" prop="group">
        <el-input clearable v-model="groupNum"
                  @blur="inputKeyUpEvent"
                  placeholder="请输入组号(1-50)"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
            type="primary"
            style="width: 100px"
            @click="startTest">开始练习
        </el-button>
        <el-button
            type="success"
            style="width:100px;margin-left: 20px"
            @click="submitRecordHear">提交
        </el-button>
        <el-button
            type="danger"
            style="width:100px;margin-left: 20px"
            @click="getHearRecord">听力记录
        </el-button>

        <div class="time-display">
          {{ formattedTime }}
        </div>

        <el-button
            plain
            type="primary"
            :disabled="isRunning || (isCountdown && initialTime === 0 && currentTime === 0)"
            @click="startTimer"
        >
          {{
            isCountdown && currentTime === 0 && initialTime > 0 && !isRunning ? '开始倒计时' : (isRunning ? '运行中' : '启动')
          }}
        </el-button>

        <el-button
            plain
            type="warning"
            :disabled="!isRunning"
            @click="pauseTimer"
        >
          暂停
        </el-button>

        <el-button
            plain
            :disabled="isRunning"
            @click="resetTimer"
        >
          重置
        </el-button>

        <el-statistic style="margin-left: 20px" :value="currentNum">
          <template #title>
            <div style="display: inline-flex; align-items: center">
              当前 / 总数
            </div>
          </template>
          <template #suffix>/ {{ total }}</template>
        </el-statistic>
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :sm="24" :lg="12" style="padding-left: 20px">
        <el-table
            border
            v-loading="loading"
            :data="pageData"
            ref="mainTable"
            stripe
        >
          <el-table-column v-if="false" type="selection" width="40" align="center"/>
          <el-table-column label="音频" align="center" width="200" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link @click="handleColumnAudioNative(scope.row,0.9)" type="primary">播放</el-button>
              <el-button link @click="handleColumnAudioNative(scope.row,0.5)" type="warning">播放(慢速)</el-button>
            </template>

          </el-table-column>
          <el-table-column v-if="false" label="编号" width="220" prop="_id"/>
          <el-table-column align="center" label="组号" width="60" prop="group">
            <template #default="scope">
              {{ scope.row.group.toLocaleString().substring(5) }}
            </template>
          </el-table-column>
          <el-table-column v-if="false" label="首字母" width="80" align="center" prop="begin">
            <template #default="scope">
              {{ scope.row.begin.toLocaleString().toLowerCase() }}
            </template>
          </el-table-column>
          <el-table-column label="拼写" width="230" align="center" prop="nameAgain">
            <template #default="scope">
              <el-input clearable @focus="handleColumnAudioNative(scope.row,null)" @blur="handleBlur(scope.row)"
                        v-model="scope.row.nameAgain"
                        placeholder="请拼写出听到的单词或词组"></el-input>
            </template>
          </el-table-column>

          <el-table-column label="状态" width="100" align="center" prop="status">
            <template #default="scope">
              <el-icon v-if="scope.row.status === true" size="28" color="green">
                <check/>
              </el-icon>
              <el-icon v-if="scope.row.status === false" size="28" color="red">
                <close/>
              </el-icon>
              <el-icon v-if="scope.row.status === null" size="28">
                <minus/>
              </el-icon>
            </template>
          </el-table-column>
          <el-table-column label="单词原文" width="120" align="center" prop="show">
            <template #default="scope">
              {{ scope.row.show ? scope.row.name : '自动显示' }}
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
            style="margin-top: 10px;float: right"
            :total="total"
            :layout="layout"
            :page-sizes="pageSizes"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />

      </el-col>
    </el-row>

    <el-dialog style="padding: 20px" title="测试结果" @close="countingDialogClose" v-model="hearResultWindow" width="600px" append-to-body>
      <el-row type="flex" justify="center">
        <el-text style="font-size: 18px;color: rebeccapurple">
          本次测试个数:{{ completeNum }}---正确个数:{{ correctNum }} ---正确率:{{ testCompleteRate }}%
        </el-text>
      </el-row>
    </el-dialog>

    <el-dialog style="padding: 20px" title="听力记录(前10条)" v-model="hearRecordWindow" width="1100px" append-to-body>
      <el-table border :data="wordTestList">
        <el-table-column label="编号" align="center" prop="id"/>
        <el-table-column label="正确" align="center" prop="correctNum"/>
        <el-table-column label="完成" align="center" prop="complete"/>
        <el-table-column label="总数" align="center" prop="wordNum"/>
        <el-table-column label="记录时间" width="180" align="center" prop="createTime"/>
        <el-table-column label="完成率" align="center" prop="rate">
          <template #default="scope">
            <span>{{ parseInt(scope.row.complete * 100 / scope.row.wordNum).toFixed(0) }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="正确率" align="center" prop="correctRate">
          <template #default="scope">
            <span>{{ parseInt(scope.row.correctRate * 100).toFixed(0) }}%</span>
          </template>
        </el-table-column>
        <el-table-column label="用时" align="center" prop="usedTime"/>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import {getHearOne, listHearByGroup, putHear, updateHear} from "@/api/word/index.js";
import '@/assets/styles/word-common.css'
import {getCurrentInstance, ref} from 'vue'
import {addWordHear, listHearRecord} from "@/api/word/wordRecord.js";
import {useTimerStore} from "@/store/timer.js";
import useUserStore from "@/store/modules/user.js";
import {ElMessage} from 'element-plus'
import {Check, Close, Minus} from "@element-plus/icons-vue";
import {isNumberStr} from "@/utils/index.js";

const timerStore = useTimerStore();
timerStore.isCountdown = false;
// 从 store 中解构 actions
const {startTimer, pauseTimer, resetTimer, toggleMode, setInitialTime} = timerStore;
// 从 store 中解构 state 和 getters (保持响应性)
const {formattedTime, isRunning, isCountdown, initialTime, currentTime} = storeToRefs(timerStore); // 添加 currentTime

let loading = false

const {proxy} = getCurrentInstance();

const openPrompt = (item, more) => {
  if (more === 1) {
    more = '单词的前两个字母为:' + item.promptBegin
  }
  if (more === 2) {
    more = '单词的前两个字母为:' + item.promptBegin + ' 单词的后两个字母为:' + item.promptEnd
  }
  if (more === 3) {
    more = '单词为:' + item.name
  }
  ElMessage({
    message: more,
    type: 'success',
    plain: true,
  })
}

const currentPage = ref(1)
const pageSize = ref(10)

const props = defineProps({
  total: {
    type: Number
  },
  page: {
    type: Number,
    default: 1
  },
  limit: {
    type: Number,
    default: 10
  },
  layout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper'
  },
  pageSizes: {
    type: Array,
    default() {
      return [10, 20, 30]
    }
  },
  pagerCount: {
    type: Number,
    default: 7
  },
  background: {
    type: Boolean,
    default: true
  },
  autoScroll: {
    type: Boolean,
    default: true
  },
  hidden: {
    type: Boolean,
    default: false
  }
})

function countingDialogClose(){
  completeNum.value = 0
  correctNum.value = 0
}

function getHeardTimesToShow1(row, times) {
  if (row.heardTimes === 3) {
    proxy.$modal.confirm("已播放 " + row.heardTimes + " 次,是否开启提示？").then(() => {
      openPrompt(row, times)
    }).catch(() => {
      proxy.$modal.msgWarning("不需要")
    })
  }
}

function getHeardTimesToShow3(row, times) {
  if (row.heardTimes % 5 === 0) {
    proxy.$modal.confirm("是否显示完整单词？").then(() => {
      row.show = true
      openPrompt(row, times)
    }).catch(() => {
      proxy.$modal.msgWarning("不需要")
    })
  }
}

let currentNum = ref()
let completeNum = ref(0)
let correctNum = ref(0)

let currentRecord = ref([])

let timeStart = ref(true)
let pageData = ref([])
let totalData = ref([])
let groupNum = ref(Math.ceil(Math.random() * 49))

let wordTestList = ref([])
let total = ref(0)
let wordEveryTime = ref(0)
let testCompleteRate = ref(0)

let hearResultWindow = ref(false)
let hearRecordWindow = ref(false)

let recordFrom = ref({})
let practiceId = ref(null)
//上一次输入记录
let lastInputRecord = ref(null)

let queryParam = ref({
  group: "",
})

// 分页大小事件触发此方法
const handleSizeChange = val => {
  pageSize.value = val
  currentPage.value = 1
  // 分页逻辑
  let start = currentPage.value > 1 ?
      (currentPage.value - 1) * val : 0
  let end = currentPage.value * val
  // 将符合条件的数据赋值给
  pageData.value = totalData.value.slice(start, end)
}
// 分页数事件触发此方法
const handleCurrentChange = val => {
  pageSize.value = pageSize.value === '' ? 10 : pageSize.value
  // 分页逻辑
  currentPage.value = val
  let start = val > 1 ?
      (val - 1) * pageSize.value : 0
  let end = val * pageSize.value

  // 将符合条件的数据赋值给
  pageData.value = totalData.value.slice(start, end)
}

initPage()

function initPage() {
  practiceId.value = Math.random().toString().substring(2)
  queryParam.value.group = "GROUP" + groupNum.value
  getData()
}

function inputKeyUpEvent() {
  if (groupNum.value === '') {
    return
  }
  if (!isNumberStr(groupNum.value) || groupNum.value % 1 !== 0) {
    proxy.$modal.msgWarning("组号必须为整数")
    return
  }
  if (groupNum.value > 50 || groupNum.value < 1) {
    proxy.$modal.msgWarning("组号必须在1-50之间")
    return
  }
  queryParam.value.group = "GROUP" + groupNum.value
  getData()
}

/**
 * 听力记录
 * */
function getHearRecord() {
  hearRecordWindow.value = true
  let query = {
    userId: useUserStore().id,
    pageSize: 10,
    pageNum: 1
  }
  listHearRecord(query).then(res => {
    if (res.code === 200) {
      wordTestList.value = res.rows;
    }
  })
}

/**
 * 初始化数据
 * */
function getData() {
  proxy.$modal.msg("正在加载组号为'" + groupNum.value + "'的数据")
  listHearByGroup(queryParam.value).then(res => {
    totalData.value = res.data
    currentNum.value = res.data.length
    total.value = res.data.length
    // console.log(total.value)
    totalData.value.forEach(item => {
      item.nameAgain = null
      item.heardTimes = 0
      item.show = false
      item.status = null
      item.wordTime = 0
      item.wordTimeEnd = 0
    })
    props.total = total.value
    // 将符合条件的数据赋值给
    pageData.value = totalData.value.slice(0, 10)
  })
}

function wordInputTimer() {
  return setInterval(() => {
    wordEveryTime.value++
  }, 1000)
}

/**
 * 输入框事件
 * */
function handleBlur(row) {

  clearInterval(row.wordTimeEnd)
  row.wordTime += wordEveryTime.value
  wordEveryTime.value = 0
  console.log(row)
  if (row.nameAgain == null || row.nameAgain.length === 0) {
    return
  }

  if (row.name.toLowerCase() !== row.nameAgain.toLowerCase()) {
    row.status = false
    proxy.$modal.msgWarning("拼写错误")
  } else {
    row.status = true
    proxy.$modal.msgSuccess("拼写正确")
  }
  //计时器开启
  if (timeStart.value) {
    timeStart.value = false
    startTimer()
  }

  if (currentRecord.value.indexOf(row._id) === -1) {
    lastInputRecord.value = row.nameAgain
    currentRecord.value.push(row._id)
    if (row.name.toLowerCase() === row.nameAgain.toLowerCase()) {
      correctNum.value++
    }
    //当前数减一
    currentNum.value--
    //完成数加一
    completeNum.value++
    //记录拼写的单词
    putRecord(row)
  } else {
    // console.log(lastInputRecord.value)
    if (lastInputRecord.value === row.nameAgain) {
      return;
    } else {
      lastInputRecord.value = row.nameAgain
    }
    if (row.name.toLowerCase() === row.nameAgain.toLowerCase()) {
      row.status = true
      correctNum.value++
    }

    getHearOne(row._id).then(res => {
      // console.log(res)
      res.data.heardTimes = row.heardTimes
      res.data.nameAgain = row.nameAgain
      updateHear(res.data).then(res => {
        // console.log(res)
        if (res.code === 200) {
          proxy.$modal.msgSuccess("更新成功")
        }
      })
    })
  }
}

//连接MYSQL数据库-插入数据
function handleInsertRecordData(data) {
  // console.log(data)
  addWordHear(data).then(res => {
    // console.log(res)
    recordFrom.value = {}
    if (res.code === 200) {
      hearResultWindow.value = true
      testCompleteRate.value = parseInt(correctNum.value * 100 / completeNum.value)
      currentRecord.value = []
      practiceId.value = Math.random().toString().substring(2)
      proxy.$modal.msgSuccess("提交成功")
      resetTimer()
      getData() //刷新列表
    }
  })
}

/**
 * 保存每一条测试记录到mongoDb
 * */
function putRecord(data) {
  // console.log(data)

  data.practiceId = practiceId.value
  // let temp = JSON.parse(JSON.stringify(data))
  data.basicId = data._id
  putHear(data).then(response => {
  })
}

/**
 * 提交记录
 * */
function submitRecordHear() {
  // console.log(formattedTime.value)
  if (completeNum.value === 0) {
    proxy.$modal.msgWarning("完成的记录个数为0")
    return
  }
  if (currentNum.value.length > 0) {
    proxy.$modal.msgWarning("还有未完成的测试")
  }

  //停止时间计时器
  pauseTimer()

  proxy.$modal.confirm('是否确认提交,已经完成的测试个数:' + completeNum.value).then(function () {
    recordFrom.value.practice = practiceId.value
    recordFrom.value.complete = completeNum.value
    recordFrom.value.times = total.value
    recordFrom.value.wordNum = total.value
    recordFrom.value.organize = queryParam.value.group

    recordFrom.value.usedTime = formattedTime.value
    recordFrom.value.correctNum = correctNum.value
    recordFrom.value.correctRate = correctNum.value / total.value

    // console.log(recordFrom.value)
    handleInsertRecordData(recordFrom.value)
  }).catch(() => {
    proxy.$modal.msg("取消提交")
  })
}

/**
 * 开始测试
 * */
function startTest() {
  proxy.$modal.msg("即将开始测试")
  completeNum.value = 0
  correctNum.value = 0

  resetTimer()
  startTimer()

  timeStart.value = false  //测试开始，计时器启动
  currentRecord.value = []
}

function handleColumnAudioNative(row, rate) {
  if (rate === undefined || rate === null) {
    rate = 0.7
    setTimeout(() => {
      const speech = new SpeechSynthesisUtterance();
      speech.text = row.name;
      speech.lang = "en-US";
      speech.volume = 1;
      speech.rate = rate;
      speech.pitch = 1;
      window.speechSynthesis.speak(speech);
    },2000)
  }

  //单个单词耗时记录
  row.wordTimeEnd =  wordInputTimer()
  // console.log(row.wordTimeEnd)

  row.heardTimes++
  startTimer()
  window.speechSynthesis.resume();
  const speech = new SpeechSynthesisUtterance();
  speech.text = row.name;
  speech.lang = "en-US";
  speech.volume = 1;
  speech.rate = rate;
  speech.pitch = 1;
  window.speechSynthesis.speak(speech);
  getHeardTimesToShow1(row, 2)
  getHeardTimesToShow3(row, 3)
}
</script>

<style scoped lang="scss">
.header {
  margin-top: 20px;
  margin-left: 20px;
}
</style>
